package eventHandling.fileHandling;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.batik.swing.JSVGCanvas;
import org.w3c.dom.Document;

/**
 * This class' purpose is to handle events of Save button of main application window
 * @author Martin
 */
public class FileSaveHandler implements ActionListener {
    private JSVGCanvas _svgCanvas;
    private JPanel _jpanel;
    
    /**
     * 
     * @param canvas svg canvas to get the svg file from
     * @param panel panel aroud the svg canvas
     */
    public FileSaveHandler(JSVGCanvas canvas, JPanel panel)
    {
        _svgCanvas = canvas;
        _jpanel = panel;
    }
    
    @Override
    public void actionPerformed(ActionEvent ae) {
            //use JFileChooser class to pick a file
        JFileChooser fc = new JFileChooser(".");
        int choice = fc.showSaveDialog(_jpanel);
        if (choice == JFileChooser.APPROVE_OPTION) {
            File saveFile = fc.getSelectedFile();

            //get document and use transformer to print it
            Document doc = _svgCanvas.getSVGDocument();
            TransformerFactory tFactory = TransformerFactory.newInstance();

            Transformer transformer = null;
            try {
                transformer = tFactory.newTransformer();
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(FileSaveHandler.class.getName()).log(Level.SEVERE, null, ex);
            }

            //hack - not printing the xml declaration now, will be added later
            //this is a fix, because the document was being printed without Doctype
            //and was not valid
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new StringWriter());

            try
            {
                result.getWriter().write("<?xml version='1.0' encoding='UTF-8'?>");            
                result.getWriter().write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">");
            }catch(IOException e){}

            //transform the xml
            try {
                transformer.transform(source, result);
            } catch (TransformerException ex) {
                Logger.getLogger(FileSaveHandler.class.getName()).log(Level.SEVERE, null, ex);
            }

            //write to a file
            try{
                FileWriter fstream = new FileWriter(saveFile);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(result.getWriter().toString());
                out.close();
            }catch (Exception e){
                System.err.println("Error: " + e.getMessage());
            }
        }
    }
}


